var mongoose=require('mongoose');
var User = mongoose.model('User');
var crypto = require('crypto');

module.exports= function (req,res,next) {
    var body=req.body;
    //console.log('api body:',body);
    if(!body.password || 'string'!==typeof body.password)return res.json({code:400,error:{message:'Bad Request(arg)'}});
    //console.log('new Post > body:',body);
    User.getByName(body.name,function (err, user) {
        if(err)return res.json({code:400,error:{message:'Bad Request'}});
        if(!user)return res.json({code:401,error:{message:'NOT AUTHORIZED'}});
        if(user.password != crypto.createHash('md5').update(body.password).digest('hex'))return res.json({code:401,error:{message:'NOT AUTHORIZED'}});
        req.user={
            _id:user._id.toString(),
            name:user.name,
            face:user.face,
            email:user.email
        };
        next();
    });
};